package com.cac.demo.service.materialScan;

import com.alibaba.fastjson.JSONObject;
import com.cac.demo.dao.dispatchSearch.MsDeliveryPackageInfoDao;
import com.cac.demo.dao.materialScan.WmsDeliverPlanDao;
import com.cac.demo.entity.materialScan.WmsDeliverPlanDTO;
import com.cac.demo.service.CallInterface.CallInterfaceService;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.util.AsyncLog;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.DateUtil;
import com.cac.demo.util.MaterialReceiptSyn;


import com.cac.demo.util.adapter.DaoException;
import com.cac.demo.util.adapter.QueryReqBean;
import com.cac.demo.util.adapter.QueryRespBean;
import com.cac.demo.util.adapter.ResponseMsg;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

/**
 * @className: WmsDeliverPlanService
 * @description: （描述这个类的作用）
 * @author:
 * @date: 2024/6/13 16:18:18 周四
 * @version: 1.0
 */
@Slf4j
@Service
public class WmsDeliverPlanService {
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Autowired
    private Environment environment;
    @Autowired
    private WorkService workService;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private MsDeliveryPackageInfoDao msDeliveryPackageInfoDao;
    @Autowired
    private AsyncLog asyncLog;
    @Autowired
    private MaterialReceiptSyn materialReceiptSyn;
    //    @Value("${pathProperty.openShopCheck}")
    private boolean isOpenShopCheck;

    /**
     * 分页查询数据
     *
     * @param queryReqBean
     * @param orderBy
     * @return
     */
    public QueryRespBean<WmsDeliverPlanDTO> searchWmsDeliverPlanDTOByPage(QueryReqBean<WmsDeliverPlanDTO> queryReqBean, String orderBy, String type, String IP, String shop) {
        QueryRespBean<WmsDeliverPlanDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            WmsDeliverPlanDTO searchParams = queryReqBean.getSearchParams();
            if(searchParams==null){
                searchParams = new WmsDeliverPlanDTO();
            }
            searchParams.setRequireShop(shop);
            Page<WmsDeliverPlanDTO> dataList = new Page<>();
            if (type.equals("handOver")) {
                dataList = wmsDeliverPlanDao.searchPlanByPage(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("return")) {
                dataList = wmsDeliverPlanDao.searchRetrunByPage(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("part")) {
                dataList = wmsDeliverPlanDao.searchPlanByItemTypeAM(searchParams, orderBy, queryReqBean.getKeyWord(), IP);
            } else if (type.equals("finPro")) {
                dataList = wmsDeliverPlanDao.searchPlanByItemTypeFS(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("Z")) {
//                dataList = wmsDeliverPlanDao.searchPlanByItemTypeZ(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("putInStorage")) {
                dataList = wmsDeliverPlanDao.searchPlanByIsReceive(searchParams, orderBy, queryReqBean.getKeyWord(), IP);
            } else if (type.equals("putIntoStorage")) {
                dataList = wmsDeliverPlanDao.searchReceiveOready(searchParams, orderBy, queryReqBean.getKeyWord(), IP);
            } else if (type.equals("rejectPart")) {
                dataList = wmsDeliverPlanDao.searchPlanPartReject(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("rejectFinPro")) {
                dataList = wmsDeliverPlanDao.searchPlanFinProReject(searchParams, orderBy, queryReqBean.getKeyWord());
            } else if (type.equals("rejectZ")) {
                dataList = wmsDeliverPlanDao.searchPlanZReject(searchParams, orderBy, queryReqBean.getKeyWord());
            }
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    public PageInfo searchPlanByItemTypeZ(int pageNum, int pageSize, String shop,HashMap map) {
        com.github.pagehelper.PageHelper.startPage(pageNum, pageSize);
        List<HashMap> data = wmsDeliverPlanDao.searchPlanByItemTypeZ(shop,map);
        return new PageInfo(data);
    }


    public PageInfo searchBeputMaterial(int pageNum, int pageSize, String ip) {
        com.github.pagehelper.PageHelper.startPage(pageNum, pageSize);
        List<HashMap> data = wmsDeliverPlanDao.searchBeputMaterial(ip);
        return new PageInfo(data);
    }

    /**
     * 根据前端按钮修改接收物料状态
     *
     * @param barcode
     * @param //funcType transfer：移交 acc：接收 reject：拒收
     * @return
     */
    @Transactional
    public ResponseMsg changeMaterialSate(String barcode, String IP, String userCode) throws ParseException {
        ResponseMsg responseMsg = new ResponseMsg();
        //首要判断，判断交接单是否存在
        Integer exist = wmsDeliverPlanDao.searchByBarCode(barcode);
        try {
            //判断当前扫码人是否与交接单单位一致

            //是否存在需要处理的条码，exist为0时，说明当前没有需要处理的交接单
            if (exist == 0) {
                responseMsg.setRetCode("201");
            } else {
                System.out.println(DateUtil.nowTime());
                wmsDeliverPlanDao.changeTransferType(barcode, DateUtil.nowTime(), IP, userCode);
                responseMsg.setRetCode("200");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseMsg.setRetCode("201");
            throw new DaoException(e.getMessage());

        } finally {
            return responseMsg;
        }
    }

    /**
     * 成品物料进行接收
     *
     * @param barcode
     * @return
     */
    @Transactional
    public ResponseMsg changeMaterialSateCP(String barcode, String IP, String userCode) {
        ResponseMsg responseMsg = new ResponseMsg();
        //首要判断，是否物流信息存在，并且协调单状态是否为已归零
        Integer exist = wmsDeliverPlanDao.searchByMesCheckQualiticationId(barcode);
        String result = null;
        try {
            //条码是否存在
            if (exist > 0) {
                //判断当前合格证是否拆分
                int index = barcode.indexOf("/");
                String qualification = "";
                //拆分过
                if (index > 1) {
                    qualification = barcode.substring(0, index);
                    //查询相同合格证条码
                    List<String> barcodes = wmsDeliverPlanDao.selectBarcodesCp(qualification);
                    //存在未移交相同合格证
                    if (barcodes.size() > 0) {
                        //将相同合格证且状态为1的条码改为2
                        for (String bar : barcodes) {
                            wmsDeliverPlanDao.changeTransferTypeByMesCheckId(bar, DateUtil.nowTime(), IP, userCode);
                            if (barcodes.size() > 1) {
                                responseMsg.setRetCode("200").setMessage("当前相同合格证条码已全部移交，请勿重复扫码！");
                            } else {
                                responseMsg.setRetCode("200").setMessage("扫码成功");
                            }
                        }
                    }
                }//未拆分过
                else {
                    if ("admin".equals(userCode)) {
                        return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
                    }
                    wmsDeliverPlanDao.changeTransferTypeByMesCheckId(barcode, DateUtil.nowTime(), IP, userCode);
                    responseMsg.setRetCode("200").setMessage("移交成功！");
                }
            } else {
                responseMsg.setRetCode("201");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return responseMsg;
        }
    }

    /**
     * yebo 2023-05-24
     * 标准件扫码移交
     */
    public ResponseMsg changeMaterialSateBJ(String barcode, String IP, String userCode) {
        ResponseMsg responseMsg = new ResponseMsg();
        //首要判断，是否物流信息存在，并且协调单状态是否为已归零
        Integer exist = wmsDeliverPlanDao.searchBjExists(barcode);
        try {
            //是否存在需要处理的条码，exist为0时，说明当前没有需要处理的交接单
            if (exist == 0) {
                responseMsg.setRetCode("201");
            } else {
                wmsDeliverPlanDao.changeTransferTypeBzj(barcode, DateUtil.nowTime(), IP, userCode);
                responseMsg.setRetCode("200");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new DaoException(e.getMessage());
        } finally {
            return responseMsg;
        }
    }

    public int searchDeliveryPlanExists(String barcode) {
        return wmsDeliverPlanDao.searchDeliveryPlanExists(barcode);
    }


    /**
     * 判断条码信息是否存在---方法
     *
     * @param barcode
     * @return
     */
    public Map isExist(String barcode) {
        Map map = new HashMap();
        //首要判断，是否物流信息存在
        Integer exist = wmsDeliverPlanDao.isLegalByBarCode(barcode);
        if (exist != null) {
            map.put("exist", "yes");
        } else {
            map.put("exist", "no");
        }
        return map;
    }

    //查询当前扫码退回的移交单主键
    public List<String> getScanBarcodeWmsDeliverPlanId(String barcode) {
        return wmsDeliverPlanDao.getScanBarcodeWmsDeliverPlanId(barcode);
    }

    //yebo 新增校验退回时是否发起协调
    public ResponseMsg checkCoordinate(String wmsDeliveryPlanId, String userCode, String userId) {
        //校验当前操作人单位是否为移交单位
        if (isOpenShopCheck) {
            int c = wmsDeliverPlanDao.searchOperIsSame(wmsDeliveryPlanId, userCode);
            if (c == 0) {
                return new ResponseMsg().setRetCode("201").setMessage("当前扫码人员单位与移交单位简码不一致，请确认!");
            }
        }
        //2023-06-27 yebo 无库存移交不校验发起协调
        String deliveryType = wmsDeliverPlanDao.queryDeliveryType(wmsDeliveryPlanId);
        if (!Objects.isNull(deliveryType) && "NOINV".equals(deliveryType)) {
            return new ResponseMsg().setRetCode("200");
        }
        //判断当前交接单是否无库存，无库存不发起协调，不校验
        int cnt = wmsDeliverPlanDao.searchCreateCoordinate(wmsDeliveryPlanId);
        if (cnt == 0) {
            return new ResponseMsg().setRetCode("201").setMessage("请确认是否发起协调并提交协调单");
        }
        return new ResponseMsg().setRetCode("200");

    }

    //yebo 新增 移交接收校验单位是否一致 未使用
    public ResponseMsg checkShopIsSame(String barcode, String userCode) {
        //校验当前操作人单位是否为移交单位
        if (isOpenShopCheck) {
            int c = wmsDeliverPlanDao.searchOperIsSame(barcode, userCode);
            if (c == 0) {
                return new ResponseMsg().setRetCode("201").setMessage("当前扫码人员单位与移交单位简码不一致，请确认!").setErrorDesc("当前扫码人员单位与移交单位简码不一致，请确认!");
            }
        }
        return new ResponseMsg().setRetCode("200");
    }

    //修改移交表退回物料状态--成品零件
    public Integer changeReturnTypeLjCP(List<String> wmsDeliverPlanIds, String barcode, String returnReason, String userId, String userCode) {
        try {
            int rsl = 0;
            for (String wmsDeliverPlanId : wmsDeliverPlanIds) {
                wmsDeliverPlanDao.updateCoordinateToZero(wmsDeliverPlanId, userId);
                rsl += wmsDeliverPlanDao.changeReturnType(wmsDeliverPlanId, barcode, returnReason, DateUtil.nowTime(), userId, userCode);
            }
            return rsl;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //修改移交表退回物料状态--成品零件
    public Integer changeReturnTypeBzj(List<String> wmsDeliverPlanIds, String barcode, String returnReason, String userId, String userCode) {
        try {
            int rsl = 0;
            for (String wmsDeliverPlanId : wmsDeliverPlanIds) {
//                wmsDeliverPlanDao.updateCoordinateToZero(wmsDeliverPlanId, userId);
                rsl += wmsDeliverPlanDao.changeReturnType(wmsDeliverPlanId, barcode, returnReason, DateUtil.nowTime(), userId, userCode);
            }
            return rsl;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }
    //获取协调单
    public String getCoordinate(String wmsDeliverPlanId) {
        try {
            return wmsDeliverPlanDao.getCoordinate(wmsDeliverPlanId);
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }
    //获取协调单ID 状态为申请归零的
    public HashMap getCoordinateByPlanId(String wmsDeliverPlanId) {
        try {
            return wmsDeliverPlanDao.getCoordinateByPlanId(wmsDeliverPlanId);
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //获取协调单
    public String getCoordinateAndUpdate(String wmsDeliverPlanId, String userId) {
        try {
            wmsDeliverPlanDao.updateCoordinateToZero(wmsDeliverPlanId, userId);
            return wmsDeliverPlanDao.getCoordinate(wmsDeliverPlanId);
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }
    //移交条件查询
    @Transactional
    public QueryRespBean<WmsDeliverPlanDTO> searchByParams(QueryReqBean<WmsDeliverPlanDTO> queryReqBean, String orderBy, String Keywords, Date startTime, Date endTime,
                                                           String funcType) {
        QueryRespBean<WmsDeliverPlanDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            WmsDeliverPlanDTO searchParams = queryReqBean.getSearchParams();
            Page<WmsDeliverPlanDTO> dataList = new Page<>();
            if (funcType.equals("return")) {
                dataList = wmsDeliverPlanDao.searchRetrunByParams(searchParams, orderBy, startTime, endTime);
            } else if (funcType.equals("handOver")) {
                dataList = wmsDeliverPlanDao.searchDeliverByParams(searchParams, orderBy, startTime, endTime);
            }
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    public WmsDeliverPlanDTO searchPlan(String wmsDeliverPlanId) {
        try {
            return wmsDeliverPlanDao.searchDeliverPlan(wmsDeliverPlanId);
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    /**
     * 删除成品预上账
     *
     * @param map ERP传入参数
     * @return
     */
    @Transactional
    public int updateDeleteCpAdvancePosting(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.deleteQuality(map);
            wmsDeliverPlanDao.deleteCpCertificate(map);
            result = wmsDeliverPlanDao.updateDeleteAdvancePosting(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        } finally {
            return result;
        }
    }

    /**
     * 删除零件预上账
     *
     * @param map ERP传入参数
     * @return
     */
    @Transactional
    public int updateDeleteLjAdvancePosting(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.deleteQuality(map);
            //  wmsDeliverPlanDao.deleteLjCertificate(map);
            result = wmsDeliverPlanDao.updateDeleteAdvancePosting(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        } finally {
            return result;
        }
    }

    /**
     * 删除零件预上账
     *
     * @param map ERP传入参数
     * @return
     */
    @Transactional
    public int updateDeleteBLjAdvancePosting(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.deleteQuality(map);
//            wmsDeliverPlanDao.deleteLjCertificate(map);
            result = wmsDeliverPlanDao.updateDeleteAdvancePosting(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        } finally {
            return result;
        }
    }


    /**
     * 预上账功能方法
     */
    public int insertAdvancePosting(HashMap map) {
        int result = 0;

        //添加ERP标志
        map.put("ATTRIBUTE8_DESC","ERP");
        //yebo 新增，判断当前交接单是否为无库存预上账，是无库存则直接改交接单状态
        if (map.containsKey("erp_delivery_type") && "NOINV".equals(map.get("erp_delivery_type"))) {
            result = wmsDeliverPlanDao.updateNoInvAdvancePosting(map);
            if (result == 0) {//未更新到数据
                result = wmsDeliverPlanDao.insertAdvancePosting(map);
            }
        } else {
            result = wmsDeliverPlanDao.insertAdvancePosting(map);
            if (map.containsKey("mes_check_qualitication_id")) {
                String checkId = map.get("mes_check_qualitication_id").toString();
                if (!"".equals(checkId) && checkId != null) {
                    //重复数据校验去重，只处理交接单状态为1，2的数据
                    wmsDeliverPlanDao.dealRepeatWdp(map);
                }
            }
        }
        /**
         * yebo 新增根据图号 型号更新备注 2023-10-26 yebo 新增添加默认设置备注
         * */
        wmsDeliverPlanDao.updateWmsDeliveryPlanRemark(map);

        return result;
    }

    public void updateDeliveryRemarkOnPreConfirm(HashMap map){
        wmsDeliverPlanDao.updateDeliveryRemarkOnPreConfirm(map);
    }

    //标准件预上账
    public int insertPreConfirmBzj(HashMap map) {
        int result = 0;
        result = wmsDeliverPlanDao.insertPreConfirmBzj(map);
        return result;
    }

    /**
     * 质量信息表
     */
    public int insertWmsQualityInfo(HashMap map) {
        int result = 0;
        try {
            map.put("ATTRIBUTE1","ERP");
            //yebo 新增判断，校验质量表是否存在数据，存在不写入数据
            int cnt = wmsDeliverPlanDao.queryQualityIsExists(map);
            if (cnt == 0) {
                result = wmsDeliverPlanDao.insertWmsQualityInfo(map);
            } else {
                log.info(">>>>>>>>>>>>>>>质量表数据已经存在，更新部分字段>>>>>>>>>>>>>>>" + map.toString());
                wmsDeliverPlanDao.updateWmsQualityInfo(map);
            }
            //xLimitLotNo 更新质量表里面限用信息
            wmsDeliverPlanDao.updateWmsQualityXLimitLotNo(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }


    /**
     * //101-ERP扫码移交
     *
     * @param barcode 移交物料条码
     * @return
     */
    @Transactional
    public String scanDelivery(String barcode, String userCode, String opUserCode, String userIp, String msgId, String barcodeType, String bzjCodeType) {
        HashMap map = new HashMap();
        String inventoryCode = "";
        JSONObject headersMap = new JSONObject();
        String func = wmsDeliverPlanDao.searchFuncByBarcode(barcode);//移交}
        String requireShop = wmsDeliverPlanDao.searchRequireShopByBarcode(barcode);
        if("143".equals(requireShop)){
            opUserCode = "486809";
        }else{
            opUserCode = "403701";
        }
        if (func.equals("ERP-101-preConfirmCp")) {//此条线不会走路
            headersMap.put("func", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.func"));
            map = wmsDeliverPlanDao.scanDeliveryCp(barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            inventoryCode = environment.getProperty("doReturnErp.doCpDeliveryReturnErp.inventoryCode");
            if("143".equals(requireShop)){
                inventoryCode += "143";
            }
            map.put("inventoryCode", inventoryCode);
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.wlLogisticsCode"));
        } else if (func.equals("ERP-101-preConfirmLj")) {//此条线不会走路
            headersMap.put("func", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.func"));
            map = wmsDeliverPlanDao.scanDeliveryLj(barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
            if("143".equals(requireShop)){
                inventoryCode += "143";
            }
            map.put("inventoryCode", inventoryCode);
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
        } else {//yebo 新增标件
            headersMap.put("func", environment.getProperty("doReturnErp.doBzjDeliveryReturnErp.func"));
            map.put("barcode", barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
            if("143".equals(requireShop)){
                inventoryCode += "143";
            }
            map.put("inventoryCode", inventoryCode);
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
        }
        //判断条码类型
        if (barcodeType.equals("LJ")) {
            map.put("barcodeType", "BARCODE");
        } else if (barcodeType.equals("CP")) {
            map.put("barcodeType", "CPHGZ");
        } else {
            map.put("barcodeType", bzjCodeType);
        }

        headersMap.put("msgId", msgId);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>map:" + map);
        JSONObject data = new JSONObject(map);
        headersMap.put("data", data);
        log.info("data: " + data.toJSONString());
        String headersmap = headersMap.toJSONString();
        log.info("==========================工控网上传_扫码移交============================");
        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("businessTab","wms_delivery_plan");
        issuedTest.put("businessCol","barcode");
        issuedTest.put("businessVal",barcode);
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
        log.info("==========================工控网上传_扫码移交============================");
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        return BData;
    }

    public List<String> scanDeliveryLjCp(String barcode, String userCode, String userIp, String msgId,String barcodeType){
        HashMap map = new HashMap();
        String inventoryCode = "",opUserCode = "";
        JSONObject headersMap = new JSONObject();
        List<String> params = new ArrayList<String>();
        List<HashMap> deliverys = wmsDeliverPlanDao.searchListByBarcode(barcode);
        for(HashMap delivery : deliverys){
            String requireShop = (String) delivery.get("requireShop");
            String func = (String) delivery.get("func");
            if("143".equals(requireShop)){
                opUserCode = "486809";
            }else{
                opUserCode = "403701";
            }
            if (func.equals("ERP-101-preConfirmCp")) {
                headersMap.put("func", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.func"));
                map = wmsDeliverPlanDao.scanDeliveryCp(barcode);
                map.put("userCode", userCode);
                map.put("userIp", userIp);
                map.put("opUserCode", opUserCode);
                inventoryCode = environment.getProperty("doReturnErp.doCpDeliveryReturnErp.inventoryCode");
                if("143".equals(requireShop)){
                    inventoryCode += "143";
                }
                map.put("inventoryCode", inventoryCode);
                map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.wlLogisticsCode"));
                if (barcodeType.equals("LJ")) {
                    map.put("barcodeType", "BARCODE");
                } else if (barcodeType.equals("CP")) {
                    map.put("barcodeType", "CPHGZ");
                }
            } else if (func.equals("ERP-101-preConfirmLj")) {
                headersMap.put("func", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.func"));
                map = wmsDeliverPlanDao.scanDeliveryLj(barcode);
                map.put("userCode", userCode);
                map.put("userIp", userIp);
                map.put("opUserCode", opUserCode);
                inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
                if("143".equals(requireShop)){
                    inventoryCode += "143";
                }
                map.put("inventoryCode", inventoryCode);
                map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
                if (barcodeType.equals("LJ")) {
                    map.put("barcodeType", "BARCODE");
                } else if (barcodeType.equals("CP")) {
                    map.put("barcodeType", "CPHGZ");
                }
            }
            headersMap.put("msgId", msgId);
            log.info(">>>>>>>>>>>>>>>>>>>>>>>map:" + map);
            JSONObject data = new JSONObject(map);
            headersMap.put("data", data);
            log.info("data: " + data.toJSONString());
            String headersmap = headersMap.toJSONString();
            log.info("==========================工控网上传_扫码移交============================");
            //工控网上传数据
            HashMap issuedTest = new HashMap();
            issuedTest.put("businessTab","wms_delivery_plan");
            issuedTest.put("businessCol","barcode");
            issuedTest.put("businessVal",barcode);
            issuedTest.put("BData", headersmap);
            issuedTest.put("msgId", msgId);
            issuedTest.put("type", headersMap.get("func"));
            log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
            log.info("==========================工控网上传_扫码移交============================");
            workService.issuedTest(issuedTest);
            //对已经转换成字符串的数据进行加密
            final Base64.Encoder encoder = Base64.getEncoder();
            String BData = encoder.encodeToString(headersmap.getBytes());
            params.add(BData);
        }

        return params;
    }

    /**
     * //101-ERP扫码退回 --CP lj
     *
     * @param barcode 移交物料条码
     * @return
     */
    @Transactional
    public String scanBackCpLj(String wmsDeliverPlanId, String barcode, String userId, String ip, String userCode, String returnReason) {
        //获取配置文件中的请求路径
        HashMap map = new HashMap();
        JSONObject headersMap = new JSONObject();
        String func = wmsDeliverPlanDao.searchFuncById(wmsDeliverPlanId);//扫码退回
        String msgId = CreatMsgId.getMsgId();

        if (func.equals("ERP-101-preConfirmCp")) {
            map = wmsDeliverPlanDao.scanBackCp(wmsDeliverPlanId, barcode);
            headersMap.put("func", environment.getProperty("doReturnErp.scanBackCp.func"));
        } else {
            map = wmsDeliverPlanDao.scanBackLj(wmsDeliverPlanId, barcode);
            headersMap.put("func", environment.getProperty("doReturnErp.scanBackLj.func"));
        }
        //判断条码类型
        if (barcode.contains("CP-")) {
            map.put("barcodeType", "CPHGZ");
        } else {
            map.put("barcodeType", "BARCODE");
        }
        map.put("userCode", userCode);
        map.put("opUserCode", userId);
        map.put("userIp", ip);
        //yebo 2023-06-27 添加扫码退回原因
       /* String returnRe = wmsDeliverPlanDao.queryDeliveryRemark(barcode);
        if(Objects.isNull(returnRe)){
            map.put("rejectNote",returnReason);
        }else{
            map.put("rejectNote",returnRe);
        }*/
        map.put("rejectNote", returnReason);
        map.put("rejectNote", "".equals(returnReason) ? "无" : returnReason);
        JSONObject data = new JSONObject(map);
        //放入请求头
        headersMap.put("data", data);
        headersMap.put("msgId", msgId);
        String headersmap = headersMap.toJSONString();
        log.info("==========================工控网上传_扫码退回============================");
        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("businessVal", wmsDeliverPlanId);
        issuedTest.put("businessTab", "wms_delivery_plan");
        issuedTest.put("businessCol", "wms_delivery_plan_id");
        issuedTest.put("type", headersMap.get("func"));
        log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
        log.info("==========================工控网上传_扫码退回============================");
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        return BData;
    }

    /**
     * //101-ERP扫码退回 --CP lj
     *
     * @param barcode 移交物料条码
     * @return
     */
    @Transactional
    public String scanBackBzj(String barcode, String userId, String ip, String userCode, String bzjCodeType, String returnReason) {
        //获取配置文件中的请求路径
        HashMap map = new HashMap();
        JSONObject headersMap = new JSONObject();
        String msgId = CreatMsgId.getMsgId();
        headersMap.put("func", "101-ERP-scanBackBzj");

        map.put("barcodeType", bzjCodeType);
        map.put("barcode", barcode);
        map.put("userCode", userCode);
        map.put("opUserCode", userId);
        map.put("userIp", ip);
        //yebo 2023-06-27
    /*    String returnRe = wmsDeliverPlanDao.queryDeliveryRemark(barcode);
        if(Objects.isNull(returnRe)){
            map.put("rejectNote",returnReason);
        }else{
            map.put("rejectNote",returnRe);
        }*/
        map.put("rejectNote", returnReason);
        JSONObject data = new JSONObject(map);
        //放入请求头
        headersMap.put("data", data);
        headersMap.put("msgId", msgId);
        String headersmap = headersMap.toJSONString();
        log.info("==========================工控网上传_扫码退回============================");
        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        issuedTest.put("businessVal", barcode);
        issuedTest.put("businessTab", "wms_delivery_plan");
        issuedTest.put("businessCol", "barcode");
        log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
        log.info("==========================工控网上传_扫码退回============================");
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        return BData;
    }

    /**
     * MES-101 现场移交回传信息 未启用，仍在配送接口里面调用出库
     */
    @Transactional
    public int shopMaterialDelivery(HashMap map) {
        int result = 0;
        try {
            //修改交接单状态
            result = wmsDeliverPlanDao.shopMaterialDelivery(map);

        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   现场驳回场景
     */
    @Transactional
    public int ShopReturnMaterial(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.ShopReturnMaterial(map);
            wmsDeliverPlanDao.MaterialRejectMatchInfo(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   现场接收场景
     */
    @Transactional
    public int ShopMaterialRece(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.ShopMaterialRece(map);
            wmsDeliverPlanDao.MaterialReceiveMatchInfo(map);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }
    public int queryIsExistsOutTransaction(HashMap map){
        //yebo 2023-11-12 判断当前交接单是否生成流水，没有的话重新出库
        int cnt = wmsDeliverPlanDao.queryIsExistsOutTransaction(map);
        if(cnt==0){
            String wmsInvOutAllotmentId = wmsDeliverPlanDao.queryWmsInvOutAllotmentId(map);
            if(wmsInvOutAllotmentId!=null&&"".equals(wmsInvOutAllotmentId)){
                map.put("WMS_INV_OUT_ALLOTMENT_ID",wmsInvOutAllotmentId);
            }else{
                return 1;
            }
        }
        return cnt;
    }

    /**
     * MES-101   二次配套场景
     */
    @Transactional
    public int SecondMatch(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.SecondMatch(map);
            wmsDeliverPlanDao.MaterialSecondMatchInfo(map);
            wmsDeliverPlanDao.InsertSecondMatch(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   物料更改场景
     */
    @Transactional
    public int SenceMaterialBg(HashMap map) {
        int result = 0;
        try {
            //更改数据保存
            wmsDeliverPlanDao.SenceUpdateInsert(map);
            //标识为0，修改操作
            if (map.get("UPDATE_FLAG").equals("0")) {
                wmsDeliverPlanDao.SenceMaterialUpdate(map);
            }
            //标识为1，新增操作
            if (map.get("UPDATE_FLAG").equals("1")) {
                wmsDeliverPlanDao.SenceMaterialInsert(map);
            }
            //标识为2，删除操作
            if (map.get("UPDATE_FLAG").equals("2")) {
                wmsDeliverPlanDao.SenceMaterialDelete(map);
            }
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }


    //MES-101  现场物料检验 2023-11-1 添加异步
    @Async
    public HashMap MakeMaterialCheck(HashMap map) {
        HashMap aLog = new HashMap();
        aLog.put("businessVal",map.get("WMS_DELIVERY_PLAN_ID"));
        asyncLog.updateAsyncLogExe(map);

        log.info("===========进入线程================"+map.toString());
        String allotmentIds = (String) map.get("WMS_INV_OUT_ALLOTMENT_ID");
        if(allotmentIds==null){
            log.info("101物料下账 占用ID为空，不做处理");
            return null;
        }
        String[] allotmentIdArray = allotmentIds.split(";");
        for(String allotmentId : allotmentIdArray){
            String msgId = CreatMsgId.getMsgId();
            //查询此占用数据的合格证号
            String hgzNo = msDeliveryPackageInfoDao.queryHgzNo(allotmentId);
            HashMap invOut = new HashMap();
            invOut.put("wmsInvOutAllotmentId", allotmentId);
            invOut.put("opUserCode", "488831");
            invOut.put("userIp", "173.53.29.67");
            if(hgzNo==null){
                invOut.put("hgzNo","");
            }else{
                invOut.put("hgzNo",hgzNo);
            }
            //校验是否已经存在出库流水 2023-10-27
            int ct = msDeliveryPackageInfoDao.queryIsExistsTransaction(invOut);
            if(ct>0){
                HashMap issuedTest = new HashMap();
                issuedTest.put("BData", invOut.toString());
                issuedTest.put("type", environment.getProperty("dispatch.sortingInvOut"));
                issuedTest.put("msgId", msgId);
                issuedTest.put("retCode", "0");
                issuedTest.put("result", "已经存在出库流水，请不要重复出库");
                issuedTest.put("businessTab", "wms_inv_out_allotment");
                issuedTest.put("businessCol", "wms_inv_out_allotment_id");
                issuedTest.put("businessVal", allotmentId);
                workService.issuedTest(issuedTest);
                continue;
            }
            //配送之后修改台账表数据
            msDeliveryPackageInfoDao.upInventory(invOut);
            //查询修改流水需要的数据
            HashMap itemInv = msDeliveryPackageInfoDao.searchInventory(invOut);
            itemInv.put("wmsInvOutAllotmentId",allotmentId);
            itemInv.put("logId",map.get("logId"));
            //配送之后修改流水表数据
            msDeliveryPackageInfoDao.insertTransaction(itemInv,hgzNo);

            JSONObject funcJson = new JSONObject(invOut);
            JSONObject resultOb = new JSONObject();
            resultOb.put("data", funcJson);
            resultOb.put("func", environment.getProperty("dispatch.sortingInvOut"));
            resultOb.put("msgId", msgId);
            //业务数据加密
            final Base64.Encoder encoder = Base64.getEncoder();
            String parameters = encoder.encodeToString(resultOb.toJSONString().getBytes());
            log.info("============================工控网上传_分拣出库==========================");
            String code = "sendBData";
            String sendScenario = "分拣出库";
            String name = "两网传输-发送业务数据";
            long beginTime = System.currentTimeMillis();
            log.info("======开始时间=======" + beginTime);
            HashMap rsl1 = callInterfaceService.sendBData(code, name, parameters, sendScenario);
            long endTime = System.currentTimeMillis();
            log.info("======消耗时间=======" + (endTime - beginTime) + "ms");
            log.info("============================工控网上传_分拣出库==========================");
            //工控网上传数据
            HashMap issuedTest = new HashMap();
            issuedTest.put("BData", resultOb.toJSONString());
            issuedTest.put("type", resultOb.get("func"));
            issuedTest.put("msgId", msgId);
            issuedTest.put("businessTab", "wms_inv_out_allotment");
            issuedTest.put("businessCol", "wms_inv_out_allotment_id");
            issuedTest.put("businessVal", allotmentId);
            workService.issuedTest(issuedTest);
            log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
        }
        asyncLog.updateAsyncLogFinish(aLog);
        return null;
    }

    /**
     * MES-101   正常退库
     */
    @Transactional
    public int MaterialReturn(HashMap map) {
        int result = 0;
        try {
            //MES-101   正常退库插入退库申请单
            wmsDeliverPlanDao.MaterialReturnApply(map);
            //修改交接单
            wmsDeliverPlanDao.MaterialReturn(map);
            //退库更新match_info表
            wmsDeliverPlanDao.MaterialReturnMatchInfo(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   故障退库
     */
    @Transactional
    public int MaterialGzReturn(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.MaterialGzReturnApply(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   报废退库
     */
    @Transactional
    public int MaterialBfReturn(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.MaterialBfReturnApply(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    /**
     * MES-101   四联单退库
     */
    @Transactional
    public int MaterialSldReturn(HashMap map) {
        int result = 0;
        try {
            wmsDeliverPlanDao.MaterialSldReturnApply(map);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }


    /**
     * 新增MDS_ITEM表数据
     *
     * @param map
     * @return
     */
    public int AddMdsItem(HashMap map) {
        int result = 0;
        try {
            map.put("SPPL_STUS_NAME","ERP");
            log.info("item表数据：" + map);
            result = wmsDeliverPlanDao.AddMdsItem(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        return result;
    }

    //接收备注上传
    public ResponseMsg saveRemark(List<HashMap> deliverys, String remark) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String opUserCode = (String) request.getSession().getAttribute("account");
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        if (deliverys.size() == 0) {
            return new ResponseMsg().setRetCode("201").setMessage("没有需要保存的数据");
        }
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            for (HashMap delivery : deliverys) {
                //接收备注
                wmsDeliverPlanDao.updateDeliveryRemark(delivery, remark);
                //反馈数据给ERP 组装数据
                HashMap receiveNote = new HashMap();
                String msgId = CreatMsgId.getMsgId();
                receiveNote.put("wmsPreDeliveryPlanId", delivery.get("wmsDeliveryPlanId"));
                receiveNote.put("remark", remark);
                receiveNote.put("recieveNote", remark);
                if (delivery.containsKey("maxStorageDate") && !Objects.isNull(delivery.get("maxStorageDate"))) {
                    //最长保管期
                    receiveNote.put("maxStorageDate", delivery.get("maxStorageDate"));
                } else {
                    receiveNote.put("maxStorageDate", " ");
                }
                if (delivery.containsKey("sealDate") && !Objects.isNull(delivery.get("sealDate"))) {
                    //油封期
                    receiveNote.put("sealDate", delivery.get("sealDate"));
                } else {
                    receiveNote.put("sealDate", " ");
                }
                if (delivery.containsKey("ensureDate") && !Objects.isNull(delivery.get("ensureDate"))) {
                    //质保期
                    receiveNote.put("ensureDate", delivery.get("ensureDate"));
                } else {
                    receiveNote.put("ensureDate", " ");
                }
                //库位号
                receiveNote.put("locatorNo", "101");
                receiveNote.put("opUserCode", opUserCode);
                receiveNote.put("userIp", IP);
                HashMap aLog = new HashMap();
                aLog.put("businessVal",receiveNote.get("wmsPreDeliveryPlanId"));
                aLog.put("busniessCol","wms_delivery_plan_id");
                aLog.put("taskName","WMS推送备注");
                aLog.put("taskType","101-ERP-saveRecieveLj");
                asyncLog.insertAsyncLog(aLog);
                //2023-11-02 yebo 保存备注为异步
                materialReceiptSyn.sendRemark(receiveNote,msgId);
            }
            platformTransactionManager.commit(transaction);
            return new ResponseMsg().setRetCode("200").setMessage("保存成功");
        } catch (Exception e) {
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            return new ResponseMsg().setRetCode("201").setMessage("保存异常");
        }
    }


    //判断工人工号是否存在
    public ResponseMsg searchWorkerCode(String usercode) {
        ResponseMsg responseMsg = new ResponseMsg();
        HashMap i = wmsDeliverPlanDao.searchWorkerCode(usercode);
        if (!Objects.isNull(i)) {
            responseMsg.setRetCode("200").setMessage("工号录入成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("未找到工号，请确认工号是否存在！");
        }
        return responseMsg;
    }



}
